﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel;
using Harkon.AppServer.cOne.Registry;

namespace Harkon.AppServer.cOne.Client
{
    public class RegistryManagement
    {
        private IDictionary<string, IRegistry> channels = new Dictionary<string, IRegistry>();

        public IRegistry CreateRegistryChannel(string hostName, int portNumber)
        {
            if (!channels.ContainsKey(hostName))
            {
                string uri = string.Format("http://{0}:{1}/cOne/Infrastructure/Registry", hostName, portNumber);
                Console.WriteLine("Creating channel for remote application server's registry on uri={0}", uri);
                BasicHttpBinding binding = new BasicHttpBinding();
                EndpointAddress address = new EndpointAddress(uri);
                channels.Add(hostName, ChannelFactory<IRegistry>.CreateChannel(binding, address));
            }
            return channels[hostName];
        }

        public void DisposeChannel(IRegistry registryChannel)
        {
            IClientChannel channel = registryChannel as IClientChannel;
            channel.Dispose();
        }

        public void DisposeAllChannels()
        {
            foreach (var registryChannel in channels.Values)
            {
                DisposeChannel(registryChannel);
            }
        }
    }
}
